import { ReactElement, useState, useEffect, Key } from 'react'
import { useParams, useLocation } from 'react-router-dom'
import { History, Location } from 'history'
import style from './index.module.less'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import Search, { formatCondition } from './components/search'
import Table from '@components/table'
import { ConditionSchema } from '@src/components/schema/condition'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import { getCaseListRequest, delCaseRequest, getPerformanceRequest } from './ajax'
import { Space, Button, message, Radio, Modal } from 'antd'
import { setSearch } from '@js/tool'
import qs from 'query-string'
import classNames from 'classnames'
import { PerformanceSchema } from '@components/schema/performanceSchema'
import { useDispatch } from 'react-redux'
import { addWindow } from '@src/redux/actions/tab'

const { confirm } = Modal

// 初始化数据
async function initData (performanceid: string, data: { [k: string]: any}, setDataSource: (v: CaseSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseListRequest(performanceid, {
    condition: formatAllCondition(data),
    page: data.page,
    limit: data.limit
  }))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
  }
}

// 格式化搜索条件
function formatAllCondition (o: { [k: string]: any }): ConditionSchema[] {
  const condition = formatCondition(o)
  if (o.type === '办案') {
    condition.push({ k: 'p.processer_appraisal', o: '=', v: 1 })
  } else if (o.type === '受理' || o.type === undefined) {
    condition.push({ k: 'p.accepter_appraisal', o: '=', v: 1 })
  }
  return condition
}

// 二次确认移除案件
function confirmDel (
  id: string,
  list: CaseSchema[],
  params: {[k: string]: any},
  setParams: (v: {[k: string]: any}) => void,
  setSelectedRowKeys: (v: Key[]) => void,
  setSelectedRows: (v: CaseSchema[]) => void
): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确认要移除这些案件吗？',
    onOk () {
      const cases = list.map(li => {
        const o = {
          id: li.performance_caseid,
          accepter_appraisal: li.accepter_appraisal,
          processer_appraisal: li.processer_appraisal
        }
        if (params.type === '受理') {
          o.accepter_appraisal = 0
        } else {
          o.processer_appraisal = 0
        }
        return o
      })
      deleteCaseFn(cases, id, params, setParams, setSelectedRowKeys, setSelectedRows).catch(e => console.error(e))
    }
  })
}

async function deleteCaseFn (
  cases: any[],
  performanceid: string,
  params: {[k: string]: any},
  setParams: (v: {[k: string]: any}) => void,
  setSelectedRowKeys: (v: Key[]) => void,
  setSelectedRows: (v: CaseSchema[]) => void
): Promise<void> {
  const hide = message.loading('移除中')
  const [e] = await awaitWrap(delCaseRequest(cases, performanceid))
  hide()
  if (e === null) {
    message.success('移除成功').then(null, null)
    setSelectedRowKeys([])
    setSelectedRows([])
    setParams({ ...params, page: 1 })
  }
}

// 初始化考核详情
async function initPerformance (id: string, setPerformance: (v: PerformanceSchema) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPerformanceRequest(id))
  if (e === null && d !== null) {
    setPerformance(d)
  }
}

interface Props {
  meta: {
    id: string
  }
}

function Main ({meta}: Props): ReactElement {
  const dispatch = useDispatch()
  const [dataSource, setDataSource] = useState<CaseSchema[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [selectedRows, setSelectedRows] = useState<CaseSchema[]>([])
  const [performance, setPerformance] = useState<PerformanceSchema | null>(null)
  const [params, setParams] = useState<{[k: string]: any}>({ type: '受理' })
  useEffect(() => {
    if (typeof meta.id === 'string') {
      initPerformance(meta.id, setPerformance).catch(e => console.error(e))
    }
  }, [meta])
  return (
    <div className={classNames(style.container, { [style.edit]: selectedRowKeys.length > 0 })}>
      <Search params={params} setParams={setParams} />
      <div className={style.table}>
        <div className={style['operate-line']}>
          <Radio.Group value={params.type} onChange={e => { setSelectedRowKeys([]); setSelectedRows([]); setParams({ ...params, type: e.target.value, page: 1 }) }}>
            <Radio.Button value='受理'>统计受理</Radio.Button>
            <Radio.Button value='办案'>统计办案</Radio.Button>
          </Radio.Group>
          <Space>
            <Button type='primary' className={style['accept-btn']} onClick={() => {
              dispatch(addWindow({ id: `performance-case-input-accepter_appraisal-${meta.id}`, title: `${performance?.title}-导入受理案件`, componentName: 'PerformanceCaseInput', meta: { id: meta.id, type: 'accepter_appraisal' } }))
            }}>导入受理案件</Button>
            <Button type='primary' onClick={() =>{
              dispatch(addWindow({ id: `performance-case-input-processer_appraisal-${meta.id}`, title: `${performance?.title}-导入办案案件`, componentName: 'PerformanceCaseInput', meta: { id: meta.id, type: 'processer_appraisal' } }))
            }}>导入办案案件</Button>
          </Space>
        </div>
        <Table params={params} setParams={setParams} columns={getColumn(dispatch, params.type)} loading={loading} total={total} dataSource={dataSource} selectable selectedRowKeys={selectedRowKeys} setSelectedRowKeys={setSelectedRowKeys} selectedRows={selectedRows} setSelectedRows={setSelectedRows} onChange={async d => await initData(meta.id, d, setDataSource, setTotal, setLoading)} />
      </div>
      {
        selectedRowKeys.length > 0 && (
          <div className={style['btn-line']}>
            <span className={style['total-message']}>
              <span>已选择</span>
              <span className={style['total-num']}>{selectedRowKeys.length}</span>
              <span>项</span>
            </span>
            <Space>
              <Button danger ghost onClick={() => { confirmDel(meta.id, selectedRows, params, setParams, setSelectedRowKeys, setSelectedRows) }}>移除</Button>
            </Space>
          </div>
        )
      }
    </div>
  )
}

export default Main
